package com.another.bidservice.utils.util.sql;

import com.another.bidservice.entity.TForm;
import com.another.bidservice.utils.util.query.ParameterProcessing;
import com.another.common.utils.common.EmptyUtil;

/**
 * 构建SQL语句工具类
 */
public class Factory {


    public static String SqlDataFactory(TForm form) {

        StringBuffer sb = new StringBuffer("");

        //分组
        if (EmptyUtil.isNotEmpty(form.getFormGroup())) {

            sb.append("Select ");

            //组装查询字段
            form.getColumns().stream().forEach(i -> sb.append(i.getColEname() + ","));

            //删除最后一个逗号
            sb.deleteCharAt(sb.length() - 1);

            sb.append(" from " + form.getFormView());

            sb.append(" where 1=1 ");

            sb.insert(0, "select count(*) from ( ");

            sb.append(" ) as t ");

            sb.append("group by " + form.getFormOrder()+" ");
        } else {

            sb.append("Select ");

            //组装查询字段
            form.getColumns().stream().forEach(i -> sb.append(i.getColEname() + ","));

            sb.deleteCharAt(sb.length() - 1);

            sb.append(" from " + form.getFormView());

            sb.append(" where 1=1 ");
        }

        if (EmptyUtil.isNotEmpty(form.getFormWhere())) {
            sb.append(form.getFormWhere() + " ");
        }

        //设置查询条件
        if (EmptyUtil.isNotEmpty(form.getQueryParameterList())) {
            String parament = ParameterProcessing.dealParameter(form.getQueryParameterList());
            sb.append(parament + " ");
        }

        //排序
        if (EmptyUtil.isNotEmpty(form.getFormOrder())) {
            sb.append("order by "+form.getFormOrder() + " ");
        }


        sb.append("LIMIT " + form.getStart() + ", " + form.getLength());

        return sb.toString();
    }


    public static String SqlCountFactory(TForm form) {
        StringBuffer sb = new StringBuffer("");

        //分组
        if (EmptyUtil.isNotEmpty(form.getFormGroup())) {

            sb.append("Select ");

            //组装查询字段
            form.getColumns().stream().forEach(i -> sb.append(i.getColEname() + ","));

            //删除最后一个逗号
            sb.deleteCharAt(sb.length() - 1);

            sb.append(" from " + form.getFormView());

            sb.append(" where 1=1 ");

            sb.insert(0, "select count(1) from ( ");

            sb.append(" ) as t");
        } else {

            sb.append("Select ");

            sb.append("count(1) ");

            sb.append(" from " + form.getFormView());

            sb.append(" where 1=1 ");
        }

        if (EmptyUtil.isNotEmpty(form.getFormWhere())) {
            sb.append(form.getFormWhere() + " ");
        }

        //设置查询条件
        if (EmptyUtil.isNotEmpty(form.getQueryParameterList())) {
            String parament = ParameterProcessing.dealParameter(form.getQueryParameterList());
            sb.append(parament + " ");
        }


        return sb.toString();
    }
}
